import json

from elasticsearch import Elasticsearch


class Search(object):

    def __init__(self):
        self.es = Elasticsearch(["192.168.31.219:9201", "192.168.31.219:9202", "192.168.31.219:9203"])

    def create_index(self):
        result = self.es.indices.create(index='news', ignore=400)
        print(result)

    def delete_index(self):
        result = self.es.indices.delete(index='news', ignore=[400, 404])
        print(result)

    def insert_data(self):
        data = {'title': '美国留给伊拉克的是个烂摊子吗', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm'}
        result = self.es.create(index='news', id=1, body=data)
        print(result)

    def insert_index(self):
        data = {'title': '美国留给伊拉克的是个烂摊子吗', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm'}
        result = self.es.index(index='news', body=data)
        print(result)

    def update_data(self):
        """
        https://github.com/elastic/elasticsearch-py/issues/1042
        更新失败
        :return:
        """
        data = {'title': '美国留给伊拉克的是个烂摊子吗', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
                'date': '2011-12-16'}
        result = self.es.update(index='news', id=1, body=data)
        print(result)

    def update_index(self):
        data = {'title': '美国留给伊拉克的是个烂摊子吗', 'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
                'date': '2011-12-16'}
        result = self.es.index(index='news', id=1, body=data)
        print(result)

    def delete_data(self):
        result = self.es.delete(index='news', id=1)
        print(result)

    def mapping_data(self):
        mapping = {
            'properties': {
                'title': {
                    'type': 'text',
                    'analyzer': 'ik_max_word',
                    'search_analyzer': 'ik_max_word'
                }
            }
        }
        self.es.indices.delete(index='news', ignore=[400, 404])
        self.es.indices.create(index='news', ignore=400)
        result = self.es.indices.put_mapping(index='news', body=mapping)
        print(result)

    def insert_data2(self):
        datas = [
            {
                'title': 'Is what the United States left to Iraq a mess',
                'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
                'date': '2011-12-16'
            },
            {'title': 'Ministry of Public Security: all school buses will enjoy the highest right of way',
             'url': 'http://www.chinanews.com/gn/2011/12-16/3536077.shtml',
             'date': '2011-12-16'
             },
            {
                'title': 'Investigation on the conflict between China and South Korea\'s fishery police: South Korean police detain one Chinese fishing boat every day on average',
                'url': 'https://news.qq.com/a/20111216/001044.htm',
                'date': '2011-12-17'
            },
            {
                'title': 'Chinese Consulate in Los Angeles shot by Asian man has surrendered',
                'url': 'http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml',
                'date': '2011-12-18'
            }
        ]

        for data in datas:
            self.es.index(index='news', body=data)

    def search(self):
        result = self.es.search(index='news')
        print(result)

    def full_search(self):
        dsl = {
            "docvalue_fields": [
                "lngid","full_field"
            ],
            "query":
                {
                    "wildcard": {
                        "title": "*长*"
                    }
                }
        }
        result = self.es.search(index='base_obj_meta_a_alias', body=dsl, params={'scroll': '1s'})
        print(json.dumps(result, indent=2, ensure_ascii=False))

    def sql_search(self):
        query = {
            "query": 'SELECT lngid FROM modify_title_info_ori_zt LIMIT 100'
        }

        results = self.es.transport.perform_request('POST', '/_sql', params={'format': 'txt'}, body=query)
        print(results)

    def sql_translate(self):
        query = {
            "query": "SELECT * from base_obj_meta_a_alias where (not (title LIKE '%河坝%' or author='12') or author_alt='23') and sub_db_id!='dfer' limit 10"
        }

        results = self.es.transport.perform_request('POST', '/_sql/translate', body=query)
        print(results)

    def get_mapping(self):
        results = self.es.indices.get_mapping(index='base_obj_meta_a_alias')
        #print(results['base_obj_meta_a_alias']['mappings']['properties'])
        print(results)

    def get_data(self):
        result = self.es.get(index='base_obj_meta_a', id='00002G4K498O7JP169DO5JPXMJR')
        print(result)

    def mget_data(self, listid: list):
        body = {
            "ids": listid
        }
        result = self.es.mget(body, index='base_obj_meta_a_alias', doc_type='_doc',
                              params={"stored_fields": "full_field"})
        # result = self.es.mget(body, index=["base_obj_meta_a_en","base_obj_meta_a_cn"], doc_type='_doc',
        #                       params={"stored_fields": "full_field"})
        print(result)

    def alias(self):
        results = self.es.transport.perform_request('GET', '/_alias/alias2')
        print(results)
        print(results.keys())


if __name__ == "__main__":
    search = Search()
    # search.mget_data(["00002H8KKJ987JP16FDG8JP1MHR", "00002HUMK5987JP169DO8JP16BR1", "00002GGGL1687JP16NDO8JP1MJR1",
    #                   "00002GGGL1687JP16NDO8JP1MJ1"])
    search.full_search()